package fencer911;

import java.nio.ByteBuffer;
import java.util.ArrayList;

/**
 * @author <a href="https://github.com/fencer911/transfer-file-by-qrcode">transfer-file-by-qrcode</a>
 * @since 2020/03
 */
public class Decoder {
	public byte[][] dataArray;
	public int curIndex=0;
	public volatile  boolean receiveAll=false;
	public volatile int total=0;
	public int size=0;
	public ArrayList<Integer> ids=new ArrayList<Integer>();

	public void receive(byte[] strBytes) {
		if(receiveAll) {
			return;
		}
		if(strBytes!=null) {
			decode(strBytes);
		}
	}
	public void decode(byte[] decodedStr){
		if(receiveAll){
			return;
		}
		ByteBuffer byteBuffer = ByteBuffer.wrap(decodedStr);
		int  total=byteBuffer.getInt();
		int  index=byteBuffer.getInt();
		if(total<1||total<=index){
			return ;
		}

		if(dataArray==null) {
			dataArray=new byte[total][];
			this.total=total;
		}
		if(dataArray[index]==null) {
			byte[] splitData=new byte[decodedStr.length-8];
			byteBuffer.get(splitData);
			dataArray[index]=splitData;
			this.curIndex=index;
		}
		this.curIndex=index;
		if(!this.ids.contains(index)){
			this.ids.add(index);
		}
		int size=this.ids.size();
		this.size=size;
		if(this.total==size){
			receiveAll=true;
		}
	}
}
